
#include <messenger/messenger.hpp>

messenger g_messenger;

void messenger::push( std::string const & message, message_data_ptr data )
{
	m_message_queue.push( message_t( message, data ) );
}

messenger::connection_t messenger::add_listener( std::string const & message, messenger::slot_t const & slot )
{
	auto listeners_iter = m_listeners.find( message );
	if ( listeners_iter == m_listeners.end( ) )
	{
		listeners_ptr_t new_listener( new listeners_t( ) );
		listeners_iter = m_listeners.insert( listeners_map_t::value_type( message, new_listener ) ).first;
	}
	
	return listeners_iter->second->connect( slot );
}

void messenger::poll( )
{
	while ( !m_message_queue.empty( ) )
	{
		message_t const & message = m_message_queue.front( );
		auto const listeners_iter = m_listeners.find( message.first );
		if ( listeners_iter != m_listeners.end( ) )
		{
			listeners_iter->second->operator()( message.first, message.second );
		}

		m_message_queue.pop( );
	}
}
